package com.freeman.cement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.mapper.*;
import com.freeman.cement.entity.*;
import com.freeman.cement.myenum.EventCatlog;
import com.freeman.cement.myenum.EventHandleResult;
import com.freeman.cement.myenum.ProcessingFlow;
import com.freeman.cement.service.AutoAssignmentService;
import com.freeman.cement.service.EventHandleService;
import com.freeman.cement.service.SmsService;
import com.freeman.cement.system.BllFrame;
import com.freeman.cement.system.WebSocketServer;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EventHandleServiceImpl implements EventHandleService {

    private static Logger logger = LoggerFactory.getLogger(EventHandleServiceImpl.class);

    @Resource
    private CjdbDao cjdbDao;
    @Resource
    private BjdbDao bjdbDao;
    @Resource
    private MessageDao messageDao;
    @Resource
    private StaffDao staffDao;
    @Resource
    private AutoAssignmentService autoAssignmentService;
    @Resource
    private SmsService smsService;
    @Resource
    private CameraDao cameraDao;

    //region 20221129

    /**
     * 接收新报警事件，并生成记录
     * 这里的nexthandler是负责该摄像头/摄像头所属的值班室
     * 这里的nexthandlerName摄像头所属指标室的名称
     */
    @Override
    public void handleNewEvent(MyEvent event, String handler, String handlerName, List<String> nexthandler, List<String> nexthandlerName) {
        //生成处理记录
        HandleRecord record = new HandleRecord();
        record.setEventId(event.getEventId());
        record.setStatus(ProcessingFlow.UNTREATED.getIndex());
        record.setStarttime(new Date());
        record.setHandler(handler);
        record.setHandlerName(handlerName);
        /**
         * 20230703
         * 接收到新事件后，可以进行自动转发也可以手动转发
         */
        AutoAssignmentConfig config = null;
        System.out.println("开始查找自动转发规则");
        System.out.println("参数如下：" + event.getEventType() + "/" + event.getCameraIndexCode());
        //查找自动转发规则
        if (event != null && StringUtils.isNotBlank(event.getEventType()) && StringUtils.isNotBlank(event.getCameraIndexCode())) {
            config = autoAssignmentService.getAssignment(event.getEventType(), event.getCameraIndexCode());
        }
        if (Objects.isNull(config) || StringUtils.isBlank(config.getUserIds())) {
            //值班室值班员手动分配转发
            record.setNexthandler(StringUtils.join(nexthandler, ","));
            record.setNexthandlerName(StringUtils.join(nexthandlerName, ","));
            if (!(cjdbDao.addHandleRecord(record) > 0)) {
                logger.error("handleNewEvent--->" + "cjdbDao.addHandleRecord执行失败:" + record.toString());
            }
        } else {
            //根据自动转发规则自动转发
            System.out.println("eventId:" + event.getEventId() + " dutyRoomId:" + event.getDutyRoomId() + " userIds:" + config.getUserIds());
            assignment(event.getEventId(), null, event.getDutyRoomId(), config.getUserIds(), EventCatlog.UNCHECKED, "报警事件处理自动转发");
            System.out.println("转发给用户id：" + config.getUserIds());
            //发送短信
            if (config.getIsSmsEnabled() != null && config.getIsSmsEnabled() && config.getUsers() != null) {
                List<String> phoneList = config.getUsers().stream().map(s -> s.getUserPhone()).filter(s -> StringUtils.isNotBlank(s)).collect(Collectors.toList());
                String phones = StringUtils.join(phoneList, ",");
                List<String> recvList = config.getUsers().stream().map(s -> s.getRealname()).collect(Collectors.toList());
                String recvs = StringUtils.join(recvList, ",");
                String content;
                try {
                    if (StringUtils.isNotBlank(event.getEventName())) {
                        content = event.getEventName();
                    } else {
                        content = "发生报警事件[" + event.getEventType() + "]";
                    }
                    
                    // 添加摄像头名称
                    if (StringUtils.isNotBlank(event.getCameraIndexCode())) {
                        try {
                            List<Camera> cameras = cameraDao.selectCameraByIndexCode(event.getCameraIndexCode());
                            if (cameras != null && !cameras.isEmpty()) {
                                Camera camera = cameras.get(0);
                                if (StringUtils.isNotBlank(camera.getCameraName())) {
                                    content += "，摄像头：" + camera.getCameraName();
                                }
                            }
                        } catch (Exception e) {
                            logger.error("获取摄像头信息失败: {}", e.getMessage());
                        }
                    }
                    
                    // 添加发生时间
                    if (StringUtils.isNotBlank(event.getHappenTime())) {
                        try {
                            String happenTime = event.getHappenTime();
                            if (happenTime.contains("T")) {
                                happenTime = happenTime.replace("T", " ");
                                if (happenTime.contains(".")) {
                                    happenTime = happenTime.substring(0, happenTime.indexOf("."));
                                }
                            }
                            content += "，发生时间：" + happenTime;
                        } catch (Exception e) {
                            logger.error("格式化时间失败: {}", e.getMessage());
                        }
                    }
                    
                    content += "。"; // 最后添加句号
                    
                    Sms sms = new Sms();
                    sms.setEventId(event.getEventId());
                    sms.setSender(null);
                    sms.setContent(content);
                    sms.setRecvList(recvs);
                    sms.setRecvPhoneList(phones);
                    
                    // 添加日志打印
                    logger.info("准备发送短信，参数如下：");
                    logger.info("事件ID: {}", event.getEventId());
                    logger.info("事件类型: {}", event.getEventType());
                    logger.info("接收人: {}", recvs);
                    logger.info("接收手机号: {}", phones);
                    logger.info("短信内容: {}", content);
                    logger.info("短信内容长度: {}", content.length());
                    
                    try {
                        smsService.sendSms(sms);
                        logger.info("短信发送成功");
                    } catch (Exception e) {
                        logger.error("短信发送失败: {}", e.getMessage(), e);
                    }
                } catch (Exception e) {
                    logger.error("构建短信内容失败: {}", e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 接警处理
     * 值班室接警处理
     * handler是值班室接警人员
     * dutyRoomId是值班室Id
     */
    @Override
    public ResponseResult answerEvent(String eventId, Integer handler, Integer dutyRoomId) {
        if (StringUtils.isBlank(eventId) || handler == null || dutyRoomId == null || handler == 0 || dutyRoomId == 0) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }

        // 获取当前登录用户
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Integer currentUserId = (Integer) request.getAttribute("userId");
        
        // 使用当前登录用户作为接警人
        handler = currentUserId;

        MyEvent event = bjdbDao.findEventDetail(eventId);
        if (event != null) {
            if (event.getStatus() == ProcessingFlow.UNTREATED.getIndex()) {
                //在cjdb中生成已接警记录
                HandleRecord record = new HandleRecord();
                record.setEventId(eventId);
                record.setStatus(ProcessingFlow.RECVALARM.getIndex());
                record.setStarttime(new Date());
                record.setHandler(handler.toString());
                //查找出接警人姓名
                Staff staff = staffDao.selectById(handler);
                if (staff != null) {
                    record.setHandlerName(staff.getRealname());
                }
                record.setDutyRoomId(dutyRoomId);
                if (!(cjdbDao.addHandleRecord(record) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
                }
                //更新bjdb中事件的状态
                MyEvent _event = new MyEvent();
                _event.setEventId(eventId);
                _event.setStatus(ProcessingFlow.RECVALARM.getIndex());
                _event.setEventReceiver(handler);
                if (!(bjdbDao.updateEvent(_event) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
                }
                return ResponseResult.success("接警成功", null);
            } else {
                throw new AppException(500001, "操作失败，报警事件" + eventId + "已被接警");
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
        }
    }

    /**
     * 值班人员关闭报警事件
     *
     * @param eventId
     * @param catlog
     * @param describe
     * @return
     * @关闭报警的值班人员的id handler
     * @关闭报警的值班室的id dutyRoomId
     */
    @Override
    public ResponseResult closeEvent(String eventId, int handler, int dutyRoomId, EventCatlog catlog, String describe) {
        if (StringUtils.isBlank(eventId)) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
        
        MyEvent event = bjdbDao.findEventDetail(eventId);
        if (event != null) {
            //在cjdb中生成关闭报警记录
            HandleRecord record = new HandleRecord();
            record.setEventId(eventId);
            record.setStatus(ProcessingFlow.CLOSED.getIndex());
            record.setStarttime(new Date());
            record.setHandler(Integer.toString(handler));
            Staff staff = staffDao.selectById(handler);
            if (staff != null) {
                record.setHandlerName(staff.getRealname());
            }
            record.setDutyRoomId(dutyRoomId);
            record.setOpinion(describe);
            if (!(cjdbDao.addHandleRecord(record) > 0)) {
                throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
            }

            //更新bjdb中事件的状态
            MyEvent _event = new MyEvent();
            _event.setEventId(eventId);
            _event.setStatus(ProcessingFlow.CLOSED.getIndex());
            _event.setDescribe(describe);
            _event.setCatlog(catlog == null ? EventCatlog.UNCHECKED.getIndex() : catlog.getIndex());
            if (!(bjdbDao.updateEvent(_event) > 0)) {
                throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
            }
            return ResponseResult.success("关闭成功", null);
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
        }
    }

    /**
     * 通知处理人，这里主要是记录值班员分派后续处理的情况
     * 因为处理人通常使用手机端访问系统，所以需要值班人员通过电话或短信通知处理人
     * 处理人得到通知后登录系统，获取分派给自己的待处理报警事件
     * @事件id eventId
     * @值班人员id handler
     * @值班室id dutyRoomId
     * @分配处理人的id集合，以,号分隔 nextHandler
     * @警情类型 catlog
     * @警情描述 describe
     * @return
     */
    @Override
    public ResponseResult assignment(String eventId, Integer handler, Integer dutyRoomId, String nextHandler, EventCatlog catlog, String describe) {
        if (StringUtils.isBlank(eventId)) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
        MyEvent event = bjdbDao.findEventDetail(eventId);
        if (event != null) {
            //在cjdb中生成关闭报警记录
            HandleRecord record = new HandleRecord();
            record.setEventId(eventId);
            record.setStatus(ProcessingFlow.NOTIFYHANDLER.getIndex());
            record.setStarttime(new Date());
            //使用自动转发时，这里为null
            if(handler != null) {
                record.setHandler(Integer.toString(handler));
                Staff staff = staffDao.selectById(handler);
                if (staff != null) {
                    record.setHandlerName(staff.getRealname());
                }
            }
            if (StringUtils.isNotBlank(nextHandler)) {
                record.setNexthandler(nextHandler);
                //final String seperator = ";,;";
                final String seperator = ",";
                final String[] nextHandlers = StringUtils.split(nextHandler, seperator);
                System.out.println("String[] nextHandlers:" + nextHandler);
                if (nextHandlers.length > 0) {
                    List<String> next_list = new ArrayList<>();
                    for (final String str : nextHandlers) {
                        Staff next = staffDao.selectById(NumberUtils.toInt(str));
                        if (next != null) {
                            next_list.add(next.getRealname());
                        }
                    }
                    record.setNexthandlerName(StringUtils.join(next_list, ","));
                }
            }
            record.setDutyRoomId(dutyRoomId);
            record.setOpinion(describe);
            if (!(cjdbDao.addHandleRecord(record) > 0)) {
                throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
            }

            //更新bjdb中事件的状态
            MyEvent _event = new MyEvent();
            _event.setEventId(eventId);
            _event.setStatus(ProcessingFlow.NOTIFYHANDLER.getIndex());
            _event.setEventHandlers(nextHandler);
            _event.setDescribe(describe);
            _event.setCatlog(catlog.getIndex());
            if (!(bjdbDao.updateEvent(_event) > 0)) {
                throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
            }
            return ResponseResult.success("已生成处理记录，为确保后续人员及时查看报警事件详情，请通过电话或短信通知处理人，如已通知请忽略。", null);
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
        }
    }

    /**
     * 由APP用户发出的将原本分配给自己处理的报警事件转推到别的处置员处理，也就是处置员可以把分配给自己处理的报警事件转推给别人
     * @海康给出的事件id eventId
     * @原处理员/App登录用户id handler
     * @转推给新的处置人员id nextHandler
     * @return
     */
    @Override
    public ResponseResult retransmitAssignment(String eventId, int handler, int nextHandler) {
        if (StringUtils.isBlank(eventId) || handler == 0 || nextHandler == 0) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
        MyEvent event = bjdbDao.findEventDetail(eventId);
        if (event != null) {
            //在cjdb中生成关闭报警记录
            HandleRecord record = new HandleRecord();
            record.setEventId(eventId);
            record.setStatus(ProcessingFlow.NOTIFYHANDLER.getIndex());
            record.setStarttime(new Date());
            //原处置人员
            record.setHandler(Integer.toString(handler));
            Staff old = staffDao.selectById(handler);
            if (old != null) {
                record.setHandlerName(old.getRealname());
            }
            //新处置人员
            record.setNexthandler(Integer.toString(nextHandler));
            Staff _new = staffDao.selectById(nextHandler);
            if(_new != null){
                record.setNexthandlerName(_new.getRealname());
            }
            if (!(cjdbDao.addHandleRecord(record) > 0)) {
                throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
            }

            //更新bjdb中事件的状态
            MyEvent _event = new MyEvent();
            _event.setId(event.getId());
            _event.setStatus(ProcessingFlow.NOTIFYHANDLER.getIndex());
            _event.setEventHandlers(Integer.toString(nextHandler));
            if (!(bjdbDao.updateById(_event) > 0)) {
                throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
            }
            return ResponseResult.success("已生成转发处理记录，为确保后续人员及时查看报警事件详情，请通过电话通知处理人，如已通知请忽略。", null);
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
        }
    }

    @Override
    public ResponseResult saveEventDescribe(String eventId, int catlog, String describe) {
        if (StringUtils.isBlank(eventId)) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
        MyEvent event = bjdbDao.findEventDetail(eventId);
        if (event != null) {
            //更新bjdb中事件的状态
            MyEvent _event = new MyEvent();
            _event.setEventId(eventId);
            _event.setDescribe(describe);
            _event.setCatlog(catlog);
            if (bjdbDao.updateEvent(_event) > 0) {
                return ResponseResult.success("保存成功", null);
            } else {
                throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
        }
    }

    @Override
    public ResponseResult getAssignmentEvent(Integer userId, String eventId, Integer status, int pageNo, int pageSize) {
        //验证分页范围
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        }

        //eventId不为空的话，直接根据eventId查找出事件详情
        if (StringUtils.isNotBlank(eventId)) {
            List<MyEvent> list = new ArrayList<>(0);
            list.add(bjdbDao.findEventDetail(eventId));
            JSONObject object = new JSONObject();
            //数据总条数
            object.put("total", list.size());
            //数据总页数
            object.put("pageNum", 1);
            object.put("pageSize", list.size());
            object.put("pages", 1);
            object.put("list", list);
            return ResponseResult.success(object);
        }
        //eventId为空的话，根据 userId 和事件 status 查找出分派给自己的事件详情
        else {
            if (userId != null) {
                //!!! 特别注意，只有PageHelper.startPage在list之前，分页查询才有效
                PageHelper.startPage(pageNo, pageSize, true);
                List<MyEvent> list = new ArrayList<>(0);

                //先获取符合模糊查询条件的eventId集合
                List<MyEvent> records = bjdbDao.selectEventIds(status, userId);
                //过滤模糊查询后不正确的结果
                List<String> eventIds = new ArrayList<>();
                records.forEach(s -> {
                    String[] users = s.getEventHandlers().split(",");
                    if (users.length > 0) {
                        for (String usr : users) {
                            if (usr.equals(userId.toString())) {
                                if (!eventIds.contains(s.getEventId())) {
                                    eventIds.add(s.getEventId());
                                }
                            }
                        }

                    }
                });

                //再获取MyEvent集合
                eventIds.forEach(s -> {
                    list.add(bjdbDao.findEventDetail(s));
                });
                PageInfo<MyEvent> pageInfo = new PageInfo<MyEvent>(list);
                return ResponseResult.success(pageInfo);
            } else {
                throw new AppException(50006, "用户id为空");
            }
        }
    }

    @Override
    public ResponseResult submitEventHandle(String eventId, int userId, String opinion) {
        if (StringUtils.isNotBlank(eventId) && userId > 0) {
            MyEvent event = bjdbDao.findEventDetail(eventId);
            //查找出是哪个值班室负责的报警事件
            //HandleRecord record = cjdbDao.findHandleRecord(eventId, ProcessingFlow.RECVALARM.getIndex());
            HandleRecord record = cjdbDao.findHandleRecord(eventId, null);
            if (event != null && record != null) {
                if(event.getStatus() != null && event.getStatus() > 0) {
                    if (event.getStatus() == ProcessingFlow.TOBEACCEPTED.getIndex()) {
                        return ResponseResult.successMsg("报警事件[" + eventId + "]，已提交待验收");
                    }
                }

                //新增cjdb中的待验收记录
                record.setEventId(eventId);
                record.setStatus(ProcessingFlow.TOBEACCEPTED.getIndex());
                record.setStarttime(new Date());
                record.setNexthandler(record.getHandler());
                record.setNexthandlerName(record.getHandlerName());
                record.setHandler(Integer.toString(userId));
                record.setOpinion(opinion);
                Staff staff = staffDao.selectById(userId);
                if (staff != null) {
                    record.setHandlerName(staff.getRealname());
                }
                if (!(cjdbDao.addHandleRecord(record) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
                }

                //更新bjdb中事件的状态
                MyEvent _event = new MyEvent();
                _event.setEventId(eventId);
                _event.setStatus(ProcessingFlow.TOBEACCEPTED.getIndex());
                if (!(bjdbDao.updateEvent(_event) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
                }

                //给负责值班室下的当班人员发送消息通知
                JSONObject message = new JSONObject();
                message.put("from", staff.getRealname());
                message.put("msg", "报警事件处理结果待验收");
                message.put("event", _event);
                Message msg = new Message();
                msg.setContent(message.toJSONString());
                msg.setEventId(_event.getEventId());
                msg.setSender(Integer.toString(userId));
                msg.setSendtime(new Date());
                //消息的接收者是值班室Id
                msg.setReceiveDutyId(record.getDutyRoomId());
                msg.setReadtimes(0);

                //给管辖该事件的值班室当班人员发送事件通知消息
                BllFrame.loginUsrsCache.forEach((k, v) -> {
                    if (Integer.toString(v.getDeptId()).equals(record.getDutyRoomId())) {
                        WebSocketServer.PushToUser(k, msg.getContent());
                    }
                });
                //将消息存入消息数据库
                messageDao.addMessage(msg);

                return ResponseResult.successMsg("已提交");

            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
    }

    @Override
    public ResponseResult confirmEventHandle(String eventId, int userId, String conclusion, EventHandleResult result) {
        if (StringUtils.isNotBlank(eventId) && userId > 0) {
            MyEvent event = bjdbDao.findEventDetail(eventId);
            //查找出是哪个值班室负责的报警事件
            //HandleRecord record = cjdbDao.findHandleRecord(eventId, ProcessingFlow.RECVALARM.getIndex());
            HandleRecord record = cjdbDao.findHandleRecord(eventId, null);
            if (event != null && record != null) {
                if(event.getStatus() != null && event.getStatus() > 0) {
                    if (event.getStatus() == ProcessingFlow.COMPLETED.getIndex()) {
                        return ResponseResult.successMsg("报警事件[" + eventId + "]，已验收");
                    }
                }

                //新增cjdb中的确认
                record.setEventId(eventId);
                record.setStatus(ProcessingFlow.COMPLETED.getIndex());
                record.setStarttime(new Date());
                record.setHandler(Integer.toString(userId));
                Staff staff = staffDao.selectById(userId);
                if (staff != null) {
                    record.setHandlerName(staff.getRealname());
                }
                record.setNexthandler("");
                record.setNexthandlerName("");
                record.setOpinion(conclusion);
                if (!(cjdbDao.addHandleRecord(record) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.ADD_EVENT_HANDLE_RECORD_ERROR);
                }

                //更新bjdb中事件的状态
                MyEvent _event = new MyEvent();
                _event.setEventId(eventId);
                _event.setStatus(ProcessingFlow.COMPLETED.getIndex());
                _event.setEndTime(new Date());
                _event.setConclusion(conclusion);
                _event.setResult(result.getIndex());
                if (!(bjdbDao.updateEvent(_event) > 0)) {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_EVENT_DATA_ERROR);
                }
                return ResponseResult.successMsg("确认成功");
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
    }


    //endregion


    /*@Override
    //nexthandler使用;间隔
    public ResultObject getAssignmentEvent(String user_code, String eventId) {
        ResultObject ro = new ResultObject();
        ro.setCode(0);
        ro.setMsg("");
        List<MyEvent> list = new ArrayList<>(0);
        //eventId不为空的话，直接根据eventId查找出事件详情
        if (StringUtils.isNotBlank(eventId)) {
            list.add(bjdbDao.findEventDetail(eventId));
            ro.setData(list);
        }
        //eventId为空的话，根据user_code查找出分派给自己的事件详情
        else {
            if (StringUtils.isNotBlank(user_code)) {
                //先获取符合模糊查询条件的eventId集合
                //下面这种查法不对，因为cjdb中永远有某个事件通知处理人这个状态的记录，所以会把过往的全部数据都查出来
                List<HandleRecord> records = cjdbDao.selectHandleRecord(ProcessingFlow.NOTIFYHANDLER.getIndex(), user_code);
                //过滤模糊查询后不正确的结果
                List<String> eventIds = new ArrayList<>();
                records.forEach(s -> {
                    String[] users = s.getNexthandler().split(";");
                    if(users.length > 0)
                    {
                        for (String usr:users)
                        {
                            if(user_code.equals(usr))
                            {
                                if(!eventIds.contains(s.getEventId()))
                                {
                                    eventIds.add(s.getEventId());
                                }
                            }
                        }

                    }
                });

                //再获取MyEvent集合
                eventIds.forEach(s -> {
                    list.add(bjdbDao.findEventDetail(s));
                });
                ro.setData(list);
            } else {
                ro.setCode(1);
                ro.setMsg("用户名不得为空");
                ro.setData(null);
            }
        }
        return ro;
    }*/

    //nexthandler使用JSONArray
//    @Override
//    public ResultObject getAssignmentEvent(String user_code, String eventId) {
//        ResultObject ro = new ResultObject();
//        ro.setCode(0);
//        ro.setMsg("");
//        List<MyEvent> list = new ArrayList<>(0);
//        //eventId不为空的话，直接根据eventId查找出事件详情
//        if (StringUtils.isNotBlank(eventId)) {
//            list.add(bjdbDao.findEventDetail(eventId));
//            ro.setData(list);
//        }
//        //eventId为空的话，根据user_code查找出分派给自己的事件详情
//        else {
//            if (StringUtils.isNotBlank(user_code)) {
//                //先获取符合模糊查询条件的eventId集合
//                List<HandleRecord> records = cjdbDao.selectHandleRecord(ProcessingFlow.NOTIFYHANDLER.getIndex(), user_code);
//                //过滤模糊查询后不正确的结果
//                List<String> eventIds = new ArrayList<>();
//                records.forEach(s -> {
//                    JSONArray array = JSONArray.parseArray(s.getNexthandler());
//                    for (Object o : array) {
//                        if (o.toString().equals(user_code)) {
//                            if (!eventIds.contains(s.getEventId())) {
//                                eventIds.add(s.getEventId());
//                            }
//                        }
//                    }
//                });
//
//                //再获取MyEvent集合
//                eventIds.forEach(s -> {
//                    list.add(bjdbDao.findEventDetail(s));
//                });
//                ro.setData(list);
//            } else {
//                ro.setCode(1);
//                ro.setMsg("用户名不得为空");
//                ro.setData(null);
//            }
//        }
//        return ro;
//    }



}
